jQuery(document).ready(function () {
    jQuery("button").on("click", function () {
        var type = jQuery(this).attr("type");
        var request = new Request();
        if (type == "Ajax") {
            setInterval(function(){ request.doAjax()},1000);
        } else if (type == "Long") {
            request.doLong();
        } else if (type == "Steam") {
            request.doSteam();
        } else if (type == "Socket") {
            request.doSocket();
        }
    });
});

var Request = function () {
    this.doAjax = function () {
        jQuery.ajax({
            url: "/ktv/Ajax/time",
            dataType: "text",
            success: function (data) {
                jQuery("#currentTimeAjax").text(data);
            }
        });

    }, this.doLong = function () {
        var request = new Request();

        jQuery.ajax({
            url: "/ktv/Long/time",
            dataType: "json",
            success: function (result) {
                if (result.code == 200) {
                    jQuery("#currentTimeLong").text(result.date);
                    request.doLong();
                }
            },
            error: function (e) {
                console.log(e);
                request.doLong();
            },
            complete: function () {
              //  request.doLong();
            }
        });

    }, this.doSteam = function () {
        var iframe = jQuery("<iframe />");
        iframe.attr("src","/ktv/Steam/time");
        iframe.hide();
        jQuery("body").append(iframe);
    }, this.doSocket = function () {
        var wsUri = "ws://localhost:8080/webSocket";

        testWebSocket();
        function testWebSocket() {
            websocket = new WebSocket(wsUri);
            websocket.onopen = function(evt) {
                onOpen(evt)
            };
            websocket.onclose = function(evt) {
                onClose(evt)
            };
            websocket.onmessage = function(evt) {
                onMessage(evt)
            };
            websocket.onerror = function(evt) {
                onError(evt)
            };
        }

        function onOpen(evt) {
            writeToScreen("CONNECTED");
            doSend("WebSocket rocks");
        }

        function onClose(evt) {
            writeToScreen("DISCONNECTED");
        }

        function onMessage(evt) {
            jQuery("#currentTimeSocket").text(evt.data);
        }

        function onError(evt) {
            writeToScreen('<span style="color: red;">ERROR:</span> '+ evt.data);
        }

        function doSend(message) {
         setInterval(function(){ websocket.send(message)},10000)  ;
        }

        function writeToScreen(message) {
           console.log(message);
        }
    }

}